import router from '@/router'
import { getToken } from '@/utils/auth'
import { getMenuList } from '@/api/menu'
import { getLocalRoute, hasRoute, saveRoute } from '@/utils/commonFunction'
import { useRoute } from 'vue-router'
import { getFirstRoute } from '@/utils/commonFunction'
import { ElMessage } from 'element-plus'
import { getAndSaveUserInfo, logoutSystem } from './utils/user'
import { getAppInfo, getUserInfo } from './api/user'
const route = useRoute()
let modules = import.meta.glob('./views/**/*.vue')
const whiteList = ['/login', '/register']

const nsmCodes = import.meta.env.VITE_NO_SHOW_MENU.split(',')

// 获取菜单列表数据
await getMenuListData()
let firstRoute = getFirstRoute()
localStorage.setItem('firstRoutePath', firstRoute.path)

await getAndSaveUserInfo()

// 获取应用是否需要登录才能进入
let infoData = await getAppInfo()
let needLoginInPage = infoData.data.enterAppBeforeLogin == 1
let loginCount = 0
router.beforeEach((to, from, next) => {
  if (!needLoginInPage) {
    next()
  } else {
    if (to.path == '/login') {
      loginCount++
      if (loginCount > 10) {
        // 跳转登录超过10次，递归调用了，，没有菜单项，跳转到404页面
        loginCount = 0
        next({ path: '/404' })
      }
    }
    if (getToken()) {
      /* 有token 输入登录的链接时 自动进入首页*/
      if (to.path === '/login') {
        next({ path: '/' })
      } else {
        next()
      }
    } else {
      // 没有token
      // 在免登录白名单，直接进入
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
      }
    }
  }
})

router.afterEach(() => {})

/**
 * 获取菜单列表数据
 *
 * 调用 getMenuList 函数获取菜单列表数据，并将获取到的数据保存到本地，
 * 同时将数据存储到 routesData 变量中，并将 routesData 添加到路由中。
 */
export async function getMenuListData () {
  return new Promise(async (resolve, reject) => {
    let res = await getMenuList()
    let routesData = res?.data
    // 整理路由数据为标准的路由结构，并存到本地
    if (routesData && routesData.length > 0) {
      routesData = generateRoutes(routesData)
      saveRoute(routesData)
      addToRouter(routesData)
      resolve('ok')
    } else {
      ElMessage.error('当前用户未配置菜单资源')
      // 清空localStorage，cookie，token等
      logoutSystem()
      reject('error')
    }
  })
}

function generateRoutes (
  routesArray: any,
  level: number = 0,
  parentPath: string = ''
) {
  for (let i = 0; i < routesArray.length; i++) {
    
    if (level == 0) {
      routesArray[i].path = '/' + routesArray[i].code
      routesArray[i].name = '/' + routesArray[i].code
      routesArray[i].meta = { title: '', icon: '' }
      routesArray[i].meta.title = routesArray[i].label
      routesArray[i].meta.icon = routesArray[i].icon
      // routesArray[i].meta.hide = nsmCodes.includes(routesArray[i].code)

    } else {
      routesArray[i].path = parentPath + '/' + routesArray[i].code
      routesArray[i].name = parentPath + '/' + routesArray[i].code
      routesArray[i].meta = { title: '', icon: '' }
      routesArray[i].meta.title = routesArray[i].label
      routesArray[i].meta.icon = routesArray[i].icon
      // routesArray[i].meta.hide = nsmCodes.includes(routesArray[i].code)
    }

    if (routesArray[i].children && routesArray[i].children.length > 0) {
      generateRoutes(routesArray[i].children, level + 1, routesArray[i].path)
    }
  }
  return routesArray
}
/**
 * 将路由信息动态追加到路由表中
 *
 * @param routesData 包含路由信息的数组
 */
function addToRouter (routesData: any[]) {
  // 初始化路由数据为一维数组
  let routerDataList: any[] = [] // 存放路由route结构信息的一维数组
  originRouteDataToOneDimensionalArray(routerDataList, routesData)

  // 将路由信息动态追加到路由表中 (可以使用一维数组遍历追加，树形结构递归追加经验证不能用)
  routerDataList.forEach(item => {
    router.addRoute('Layout', item)
  })
}

/**
 * 将树形路由原始数据转为一维数组
 *
 * @param routerDataList 存储路由数据的数组
 * @param routesDataList 原始路由数据树形结构
 */
function originRouteDataToOneDimensionalArray (
  routerDataList: any[],
  routesDataList: any[]
) {
  for (let i = 0; i < routesDataList.length; i++) {
    let ri = routesDataList[i]

    if (ri.type == '3') {
      // 检查自定义页面是否存在
      if (!modules[`./views/${ri.data.path}.vue`]) {
        console.error(
          `项目中包含自定义页面，且未在项目中找到此页面文件：/src/views/${ri.data.path}.vue`
        )
      }
      let route = {
        path: ri.path,
        name: ri.code,
        component: modules[`./views/${ri.data.path}.vue`],
        children: []
      }
      routerDataList.push(route)
    } else {
      let route = {
        path: ri.path,
        name: ri.code,
        component: () => import('@/components/PageContent.vue'),
        children: []
      }
      routerDataList.push(route)
    }

    if (ri.children && ri.children.length > 0) {
      originRouteDataToOneDimensionalArray(routerDataList, ri.children)
    }
  }
}
